package com.utils {
import com.fingerplay.main.model.Player;

import fairygui.GButton;

import laya.events.Event;

/**
 * 长按、点击按钮绑定
 * @author boge
 *
 */
public class LongPressBtn {

	/** 按下判定长按的间隔时间 */
	private const HOLD_TRIGGER_TIME:int = 500;
	/** 被绑定的按钮 */
	private var btn:GButton;
	/** 长按后回调方法 */
	private var callback:Function;
	/** 玩家长时间按下 */
	private var isApeHold:Boolean;
	/** 执行回调方法  附带参数 */
	private var args:Array;

	/**
	 * 创建一个监听
	 * @param btn 绑定按钮
	 * @param callback 回调方法
	 * @param args 执行回调方法  附带参数
	 *
	 */
	public function LongPressBtn(btn:GButton, callback:Function, args:Array) {
		this.btn = btn;
		this.callback = callback;
		this.args = args;

		btn.on(Event.MOUSE_DOWN, this, downHandler);
		btn.onClick(this, clickHandler);

	}

	/** 点下按钮 */
	private function downHandler(e:Event):void {
		if (Player.inst.status == 1) {
			Laya.timer.once(HOLD_TRIGGER_TIME, this, onHold);
			Laya.stage.on(Event.MOUSE_UP, this, upHandler);
		}
	}

	/** 松开按钮 */
	private function upHandler(e:Event):void {
		isApeHold = false;
		Laya.timer.clear(this, xiazhuHandler);
		// 如果未触发hold，终止触发hold
		Laya.timer.clear(this, onHold);
		Laya.stage.off(Event.MOUSE_UP, this, upHandler);
	}

	private function onHold(e:Event):void {
		isApeHold = true;
		Laya.timer.loop(100, this, xiazhuHandler);
	}

	private function xiazhuHandler():void {
		if (isApeHold) {
			clickHandler(null);
		} else {
			Laya.timer.clear(this, xiazhuHandler);
		}
	}

	private function clickHandler(e:Event):void {
		if (e != null) e.stopPropagation();
		if (Player.inst.status == 1 || Player.inst.status == 4) {
			if (callback) callback.apply(null, args);
		}
	}

	public function dispose():void {
		btn.off(Event.MOUSE_DOWN, this, downHandler);
		btn.offClick(this, clickHandler);
	}

}

}